/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jbpm.test;

import java.io.File;
import java.nio.file.Files;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.jbpm.test.persistence.util.PersistenceUtil;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.command.KieCommands;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.InternalKieBuilder;
import org.kie.scanner.KieMavenRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class JbpmTestCase extends JbpmJUnitBaseTestCase {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    protected static final String EMPTY_CASE = "EmptyCase.bpmn2";
    
    public JbpmTestCase() {
        this(true);
    }

    public JbpmTestCase(boolean persistence) {
        this(persistence, persistence);
    }

    public JbpmTestCase(boolean setupDataSource, boolean sessionPersistence) {
        this(setupDataSource, sessionPersistence, "org.jbpm.test.persistence");
    }

    public JbpmTestCase(boolean setupDataSource, boolean sessionPersistence, String persistenceUnit) {
        super(setupDataSource, sessionPersistence, persistenceUnit);
    }

    @Rule
    public TestRule watcher = new TestWatcher() {

        @Override
        protected void starting(Description description) {
            System.out.println(" >>> " + description.getMethodName() + " <<< ");
        }

        @Override
        protected void finished(Description description) {
            System.out.println();
        }

    };

    @Override
    protected Properties getDataSourceProperties(){
        Properties dsProps = PersistenceUtil.getDatasourceProperties();
        dsProps.setProperty("POOL_CONNECTIONS", "false");
        return dsProps;
    }

    public KieSession createKSession(String... process) {
        createRuntimeManager(process);
        return getRuntimeEngine().getKieSession();
    }

    public KieSession createKSession(Map<String, ResourceType> res) {
        createRuntimeManager(res);
        return getRuntimeEngine().getKieSession();
    }

    public KieSession restoreKSession(String... process) {
        disposeRuntimeManager();
        createRuntimeManager(process);
        return getRuntimeEngine().getKieSession();
    }

    public void assertProcessInstanceNeverRun(long processId) {
        Assertions.assertThat(getLogService().findProcessInstance(processId)).as("Process has been running").isNull();
    }

    protected static KieServices getServices() {
        return KieServices.Factory.get();
    }

    protected static KieCommands getCommands() {
        return getServices().getCommands();
    }

    protected byte[] createAndDeployJar(KieServices ks, ReleaseId releaseId, Resource... resources) throws Exception {
        KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(releaseId);
        for (int i = 0; i < resources.length; i++) {
            if (resources[i] != null) {
                kfs.write(resources[i]);
            }
        }
        KieBuilder kieBuilder = ks.newKieBuilder(kfs);
        ((InternalKieBuilder) kieBuilder).buildAll(o -> true);
        Results results = kieBuilder.getResults();
        if (results.hasMessages(Message.Level.ERROR)) {
            throw new IllegalStateException(results.getMessages(Message.Level.ERROR).toString());
        }
        InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule(releaseId);
        byte[] pomXmlContent = IOUtils.toByteArray(kieModule.getPomAsStream());
        File pom = new File("target",
                UUID.randomUUID().toString());
        Files.write(pom.toPath(),
                pomXmlContent);
        KieMavenRepository.getKieMavenRepository().installArtifact(releaseId,
                kieModule,
                pom);

        byte[] jar = kieModule.getBytes();
        return jar;
    }

}

